package com.itheima.service.impl;

import com.itheima.common.TokenException;
import com.itheima.enums.RedisEnum;
import com.itheima.enums.TokenErrorEnum;
import com.itheima.service.RefreshTokenService;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.TokenVo;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <h1>刷新token服务实现层</h1>
 *
 * @author <a href="11n_yd2h5e1jx8@dingtalk.com">叶世铭</a>
 * @since 2023/2/2
 */
@Service
public class RefreshTokenServiceImpl implements RefreshTokenService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public TokenVo refreshToken(HttpServletRequest request) throws TokenException {
        String refreshToken = request.getHeader("refreshToken");
        Claims claims = JwtUtil.parseRefreshToken(refreshToken);
        if (claims.getExpiration().before(new Date())) {
            throw new TokenException(TokenErrorEnum.REFRESH_TOKEN_ADVENT.name());
        }
        String userId = (String) claims.get("userId");
        String studentAccessToken = JwtUtil.createStudentAccessToken(userId);
        String studentRefreshToken = JwtUtil.createStudentRefreshToken(userId);
        TokenVo tokenVo = new TokenVo();
        tokenVo.setAccessToken(studentAccessToken);
        tokenVo.setRefreshToken(studentRefreshToken);
        stringRedisTemplate.opsForValue().set(RedisEnum.LOGIN_CHECK.getRedis() + userId, studentAccessToken);
        return tokenVo;
    }
}
